package com.ninetaildemonfox.zdl.socialproject.mvp.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.utils.Preferences;
import com.kongzue.dialog.interfaces.OnDismissListener;
import com.kongzue.dialog.v3.TipDialog;
import com.kongzue.dialog.v3.WaitDialog;
import com.ninetaildemonfox.zdl.socialproject.base.BaseActivity;
import com.ninetaildemonfox.zdl.ninetaildemonfox.utils.AppManager;
import com.ninetaildemonfox.zdl.socialproject.R;
import com.ninetaildemonfox.zdl.socialproject.mvp.contract.LoginContract;
import com.ninetaildemonfox.zdl.socialproject.mvp.presenter.LoginPresenter;
import com.orhanobut.logger.Logger;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author NineTailDemonFox
 * @date 2019/7/16 15:27
 * 功能描述： 登录界面
 * 联系方式：1037438704@qq.com
 */
public class LoginActivity extends BaseActivity implements LoginContract {
    @BindView(R.id.text_center)
    TextView textCenter;
    @BindView(R.id.edit_phone)
    EditText editPhone;
    @BindView(R.id.edit_psd)
    EditText editPsd;
    @BindView(R.id.iamge_eye)
    ImageView iamgeEye;
    @BindView(R.id.text_login)
    TextView textLogin;
    @BindView(R.id.text_forget)
    TextView textForget;
    @BindView(R.id.text_register)
    TextView textRegister;
    @BindView(R.id.text_qq)
    TextView textQq;
    @BindView(R.id.text_wx)
    TextView textWx;
    private boolean aBoolean = false;

    public LoginPresenter loginPresenter;

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_login;
    }

    @Override
    protected void onInitialization(Bundle bundle) {
        requestPemissions();
        loginPresenter = new LoginPresenter(this);
        loginPresenter.setContext(LoginActivity.this);
        textCenter.setText("登录");
        String phone = Preferences.getInstance().getString(this, "name", "phone");
        String psd = Preferences.getInstance().getString(this, "name", "psd");
        Logger.d(phone + "===============" + psd);
        editPhone.setText(phone);
        editPsd.setText(psd);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @OnClick({R.id.iamge_eye, R.id.text_login, R.id.text_forget, R.id.text_register, R.id.text_wx, R.id.text_qq})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iamge_eye:
                if (aBoolean == false) {
                    aBoolean = true;
                    iamgeEye.setSelected(aBoolean);
                    //设置EditText的密码为可见的
                    editPsd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    aBoolean = false;
                    iamgeEye.setSelected(aBoolean);
                    //设置密码为隐藏的
                    editPsd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                editPsd.setSelection(editPsd.getText().length());
                break;
            case R.id.text_login:
//                startActivity(new Intent(LoginActivity.this, SelectiveSexActivity.class));
                loginPresenter.getLogin(editPhone.getText().toString().trim(), editPsd.getText().toString().trim());
                break;
            case R.id.text_forget:
                // 1,忘记密码
                AuthenticateLoginActivity.start(this, 1);
                break;
            case R.id.text_register:
                //注册
                AuthenticateLoginActivity.start(this, 2);
                break;
            case R.id.text_wx:
                //wx
                loginPresenter.getThreeLogin("2");
                break;
            case R.id.text_qq:
                //qq
                loginPresenter.getThreeLogin("1");
                break;
            default:
        }
    }


    @Override
    public void loginSuccess(final Map<String, String> getData) {
        Preferences.getInstance().commit(me, "name", "phone", getData.get("account"));
        Preferences.getInstance().commit(me, "name", "psd", editPsd.getText().toString().trim());
        Preferences.getInstance().commit(me, "user", "token", getData.get("token"));
        Preferences.getInstance().commit(me, "user", "sex", getData.get("sex"));
        Preferences.getInstance().commit(me, "user", "vip", getData.get("vip"));
        //判断是否已经填写
        Preferences.getInstance().commit(me, "user", "nickname", getData.get("nickname"));
        //判断是否已经填写
        Preferences.getInstance().commit(me, "user", "invite_code", getData.get("invite_code"));
        //环信登录
        huanxin(getData);

        TipDialog.show(me, "登录成功", TipDialog.TYPE.SUCCESS).setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                // 性别 1男 2 女
                String string = Preferences.getInstance().getString(me, "user", "sex");
                Logger.d("=========登录界面获取的性别==========" + string);
                if (TextUtils.isEmpty(string) || string.equals("0")) {
                    startActivity(new Intent(me, SelectiveSexActivity.class));
                } else if (string.equals("1")) {
                    if (!TextUtils.isEmpty(getData.get("invite_code"))) {
                        AppManager.getInstance().killAllActivity();
                        startActivity(new Intent(me, MainActivity.class));
                        return;
                    }
                    startActivity(new Intent(me, WelcomeActivity.class));
                } else if (string.equals("2")) {
                    if (!TextUtils.isEmpty(getData.get("nickname"))) {
                        AppManager.getInstance().killAllActivity();
                        startActivity(new Intent(me, MainActivity.class));
                        return;
                    }
                    EditorialMaterialsActivity.start(me, 1);
                }
            }
        });
    }

    private void huanxin(Map<String, String> getData) {
        EMClient.getInstance().login(getData.get("id") + "m", "123456", new EMCallBack() {//回调
            @Override
            public void onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                Log.d("huanxin", "登录聊天服务器成功！");
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                Log.d("huanxin", "登录聊天服务器失败！");
            }
        });
    }

    @Override
    public void loginFailed(String msg) {
        ShowToast(this, msg);
    }

    @Override
    public void showLoading() {
        WaitDialog.show(me, "正在登录");
    }

    public static void start(Context me) {
        me.startActivity(new Intent(me, LoginActivity.class));
    }

    private void requestPemissions() {
        requestPermission(new OnPermissionResponseListener() {
                              @Override
                              public void onSuccess(String[] permissions) {

                              }

                              @Override
                              public void onFail() {
                                  startAppSettings();
                              }
                          }, Manifest.permission.CAMERA, //相机
                Manifest.permission.WRITE_EXTERNAL_STORAGE,//写入
                Manifest.permission.ACCESS_COARSE_LOCATION,//定位
                Manifest.permission.ACCESS_FINE_LOCATION,//位置权限
                Manifest.permission.RECORD_AUDIO,//音频权限
                Manifest.permission.READ_EXTERNAL_STORAGE//读取
        );
    }
}
